package com.wu.demo.common.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 自定义手机号验证
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {
    private boolean required = false;
    // 定义的手机号验证正则表达式
    private Pattern pattern = Pattern.compile("1([3-9])\\d{9}");

    @Override
    public void initialize(Phone constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(required) {
            return pattern.matcher(s).matches();
        }else {
            if(StringUtils.isEmpty(s.trim())) {
                return false;
            }else{
                return pattern.matcher(s).matches();
            }
        }
    }


}
